<template>
  <div class="security-document-left">
    <group-title/>
    <div class="security-document-l1">
      <div class="security-document-l1-title">
        <category-title filter title="实时告警" title-sub="Real-time Alarm">
          <div v-if="pageConfig.type === '2'" class="weigui" style="color: #9CDEFF">
            <!--                style="width: 120px"-->
            <a-select
                ref="select"
                v-model:value="wanguiSelect"
                :bordered="false"
                :options="selectOp"
                size="small"
                @change="wanggeiChange"
            ></a-select>
          </div>
          <div v-if="pageConfig.type === '1'" class="tiantai" @click="kljChange">
            {{ klj ? "切换抓拍" : "切换客流机" }}
          </div>
        </category-title>
      </div>
      <div class="timeline-box">
        <!--        <timeline-info />-->
        <info-block :datas="Ldata" :type="pageConfig.type" @change="leftChange"></info-block>
      </div>
    </div>
  </div>
  <div class="security-document-right">
    <div class="search-box">
      <search-bar ref="searchBar"
                  :style="{ zIndex: 3 }"
                  date placeholder="搜索更多安防事件"
                  @dateChange="dateChange"
                  @search="onSearch"
      />
    </div>
    <div v-if="klj && pageConfig.type ==='1'" class="event-box">
      <event-info
          v-for="(item, index) in R1List"
          :key="index"
          :columns="r1KljColumn"
          :datas="item"
          :selected="index === selectedEvent"
          @img="videoChange"
      />
    </div>
    <div v-else ref="listRef" class="event-box" @scroll="scrollEvent">
      <event-info
          v-for="(item, index) in R1List"
          :key="index"
          :columns="r1EventColumn"
          :datas="item"
          :selected="index === selectedEvent"
          @arrow="onEventArrowClick"
          @button="(btnIndex) => onEventButtonClick(index, btnIndex, item)"
          @click="onEventClick(index)"
      />
    </div>
    <dialog-submit v-if="showDialogSubmit" :data="submitData" :show="showDialogSubmit" @close="onDialogSubmitClose"
                   @submit="onDialogSubmitSubmit"
    />
    <dialog-event :data="eventData"
                  :show="showDialogEvent" @close="onDialogEventClose"
                  @submit="onDialogEventSubmit"
    />

  </div>
  <DialogCamera v-if="showPreview" :url="previewUrl" :url-list="previewUrlList"
                @close="showPreview = false"
  />

</template>

<script setup>
import {inject, onBeforeUnmount, ref} from "vue";
import {Ldata, r1EventColumn, r1KljColumn, selectOp} from "./data.js";
import GroupTitle from "@/components/customs/group-title/index.vue";
import CategoryTitle from "@/components/customs/category-title/index.vue";
import SearchBar from "@/components/customs/search-bar/index.vue";
import EventInfo from "@/components/customs/event-info/index.vue";
import DialogSubmit from "@/components/customs/dialog-submit/index.vue";
import DialogEvent from "@/components/customs/dialog-event/index.vue";
import {CameraVideo, DocumentCount, DocumentGJCl, SecurityL3, Send2DD} from "@/common/customs/security";
import {reactive} from "@vue/reactivity";
import InfoBlock from "@/components/customs/info-block";
import {onMounted} from "@vue/runtime-core";
import {dateTransform} from "@/common/tool";
import dayjs from "dayjs";
import DialogCamera from "@/components/customs/dialog-camera/index.vue";

const showPreview = ref(false);
const previewUrl = ref("");
const previewUrlList = ref([]);
const onPageChange = inject("pageChange");
const pageConfig = reactive({
  page: 1,
  page_size: 12,
  total: 0,
  type: "",
  sj: ""
});
const wanguiSelect = ref("");
const time = ref("");
const listTime = ref();
const selectedEvent = ref(-1);
const searchText = ref("");
const showDialogSubmit = ref(false);
const showDialogEvent = ref(false);
const klj = ref(false);
const scrollList = ref();
const R1List = ref([]);
const submitData = ref({});
const eventData = ref({});
const smartObject = inject("smartObject");
const isLoading = inject("isLoading");
const listRef = ref();
const searchBar = ref();
const loging = ref(false);
const pageEnd = reactive({
  page: 1,
  isEnd: false,
});

const onEventClick = (index) => {
  selectedEvent.value = index;
};

const onEventButtonClick = (index, btnIndex, item) => {
  if (btnIndex === 0) {
    showDialogSubmit.value = true;
    submitData.value = item;
  } else if (btnIndex === 1) {
    eventData.value = item;
    showDialogEvent.value = true;
  }
};

const onEventArrowClick = (data) => {
  if (data.XH) {
    smartObject.xh = data.XH;
    smartObject.sj = dateTransform(new Date(data.sj)).date;
    onPageChange(23);
  } else {
    smartObject.msr = data.sjid;
    onPageChange(24);
  }
};

const onDialogSubmitSubmit = async (data) => {
  const api = new Send2DD();
  api.data({
    ...data,
  });
  await api.send();
  const res = await api.getDatas();
  getList();
  showDialogSubmit.value = false;
};

const onDialogSubmitClose = () => {
  showDialogSubmit.value = false;
};

const onDialogEventSubmit = async (cljg) => {
  const api = new DocumentGJCl();
  api.query(["Hkgj-edit", eventData.value.id]);
  api.data({
    cljg: cljg.cljg
  });
  await api.send();
  const res = await api.getDatas();
  getList();
  getLeft();
  showDialogEvent.value = false;
};

const onDialogEventClose = () => {
  showDialogEvent.value = false;
};

const getList = async (nextPage = false) => {
  if (klj.value && pageConfig.type === "1") {
    const api = new SecurityKlj();
    await api.send();
    const {data} = await api.getDatas();
    let list = data.map(i => {
      let num = i.allInNum - i.allOutNum || 0;
      let time = dayjs(i.sj);
      let newTime = dayjs().diff(time, "minute");
      i.dqrs = num;
      i.dlsc = newTime || 0;
      i.sjxq = `${i.name},总计进入${i.allInNum || 0},离开${i.allOutNum || 0}人,当前逗留${num || 0}人，逗留时长${newTime || "0"}分钟`;
      return {
        ...i,
        _title: i.name,
        _type: "red",
        _tag: {
          type: "fill-red",
          back: "#699DF8",
          text: "客流机",
        },
        _hexagon: {
          type: i.dqrs === 0 ? "orange" : "blue",
          text: i.dqrs === 0 ? "无人" : "有人",
        },
      };
    });
    R1List.value = list;
  } else {
    const api = new SecurityL3();
    let params = {
      page_size: pageConfig.page_size,
      page: pageConfig.page,
      name: searchText.value,
      type: pageConfig.type,
      sj: pageConfig.sj,
    };
    if (pageConfig.type === "2") {
      params.is_wg = wanguiSelect.value;
    }
    if (smartObject.gjxh) {
      params.XH = smartObject.gjxh;
    }
    if (smartObject.gjtype) {
      // params.gq_type = smartObject.gjtype;
    }
    if (smartObject.gjid) {
      params.se_id = smartObject.gjid;
    }
    api.params(params);
    await api.send();
    const {data} = await api.getDatas();
    let list = data.data.map(i => {
      return {
        ...i,
        _title: i.name,
        _type: "red",
        _tag: {
          type: "fill-red",
          back: ["", "#699DF8", "#3B817E", "#B575F5", "#CFA162", "#C12A1E"][i.type],
          text: ["", "抓拍", ["", "晚归告警", "未归告警", "考勤后外出"][i.is_wg], "上网行为", "失联", "异常人员"][i.type],
        },
        _hexagon: {
          type: i.is_type === 1 ? "orange" : "blue",
          text: i.is_type === 1 ? "已处理" : "未处理",
        },
        _buttons: [
          {
            type: "fill-blue",
            title: "发送",
          },
          {
            dis: i.is_type === 1,
            type: i.is_type === 1 ? "fill-gray" : "fill-orange",
            title: i.is_type === 1 ? "已处理" : "处理",
          },
        ],
      };
    });

    if (nextPage) {
      R1List.value.push(...list);
      loging.value = false;
    } else {
      pageConfig.page = 1;
      // scrollList.value.scrollTop = 0
      R1List.value = list;
    }
    if (pageConfig.page >= data.last_page) {
      pageEnd.isEnd = true;
    } else {
      pageEnd.isEnd = false;
    }
  }
};

const getLeft = async () => {
  if (listTime.value) {
    clearInterval(listTime.value);
  }
  listTime.value = setInterval(getLeft, 60000);

  const api = new DocumentCount();
  let params = {
    sj: pageConfig.sj,
    name: searchText.value,
    XH: smartObject.gjxh
  };
  if (smartObject.gjid) {
    params.se_id = smartObject.gjid;
  }
  if (pageConfig.type === "2") {
    params.is_wg = wanguiSelect.value;
  }
  api.params(params);
  await api.send();
  const {data} = await api.getDatas();
  Ldata.value.forEach(i => {
    i.dai = data[`${i.key}dcl`];
    i.zong = data[i.key];
  });
};

const onSearch = (text) => {
  pageConfig.page = 1;
  searchText.value = text;
  getList();
  getLeft();
};

const kljChange = () => {
  klj.value = !klj.value;
  getList();
};
const wanggeiChange = () => {
  R1List.value = [];
  pageConfig.page = 1;
  getList();
  getLeft();

};
const leftChange = (type) => {
  // smartObject.gjtype = 0
  // smartObject.gjid = 0
  pageConfig.type = type;
  pageConfig.page = 1;
  getList();
  getLeft();

};

const dateChange = (date) => {
  pageConfig.page = 1;
  pageConfig.sj = date ? date.format("YYYY-MM-DD") : "";
  // smartObject.gjxh = "";
  getList();
  getLeft();
};

const videoChange = async (item) => {
  if (!item.cameraIndexCode) {
    return;
  }
  previewUrlList.value = [];
  isLoading.value = true;
  try {
    const api = new CameraGY();
    api.params({
      name: item.lou,
    });
    await api.send();
    const {data} = await api.getDatas();
    previewUrlList.value = data;
    const res = new CameraVideo();
    res.params({
      cameraIndexCode: data[0].cameraIndexCode,
      id: data[0].id,
    });
    await res.send();
    const {data: videoUrl} = await res.getDatas();
    previewUrl.value = videoUrl;
    showPreview.value = true;
    isLoading.value = false;
  } catch (e) {
    console.log(e);
    isLoading.value = false;
  }
};
const scrollEvent = async (event) => {
  if (Math.ceil(event.currentTarget.scrollTop + event.currentTarget.clientHeight) >= event.currentTarget.scrollHeight - 30 && !loging.value) {
    if (!pageEnd.isEnd) {
      pageConfig.page++;
      loging.value = true;
      getList(true);
    }
  }
};
onMounted(() => {
  if (smartObject.gjtype) {
    pageConfig.type = "2";
    let time = dayjs();
    if (smartObject.gjsj) {
      time = time.subtract(1, "day");
    }
    searchBar.value.dateValue = time;
    wanguiSelect.value = smartObject.gjtype;
    pageConfig.sj = time.format("YYYY-MM-DD");
  }

  getList();
  getLeft();
});

onBeforeUnmount(() => {
  smartObject.gjtype = 0;
  smartObject.gjid = 0;
  smartObject.gjxh = "";
  smartObject.gjsj = false;
  pageConfig.sj = "";
  pageConfig.type = "";
  clearInterval(listTime.value);

});

</script>

<style lang="less" scoped>
@import "./index.less";
</style>
